package com.tnsw.facebookautoliker;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONObject;

import com.facebook.Session;
import com.tnsw.coreutils.AsyncManager;
import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.MyUncaughtExceptionHandler;
import com.tnsw.coreutils.UIUtils;
import com.tnsw.coreutils.database.RecordBase;
import com.tnsw.coreutils.files.FileUtils;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.queuemanager.QDelegateManager;
import com.tnsw.coreutils.text.TextUtils;
import com.tnsw.coreutils.ui.BitmapCache;
import com.tnsw.facebookautoliker.base.FragmentBase;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.database.FriendsList;
import com.tnsw.facebookautoliker.database.SelfInfo;
import com.tnsw.facebookautoliker.dialog.LogoutDialog;
import com.tnsw.facebookautoliker.dialog.MyDialogOnClickListener;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.GeneralManager;
import com.tnsw.facebookautoliker.helper.command.GetSelfPost;
import com.tnsw.facebookautoliker.helper.command.LikeManager;
import com.tnsw.facebookautoliker.helper.command.SQLiteSelect;
import com.tnsw.facebookautoliker.services.AutoLikerService;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.test.UiThreadTest;
import android.text.format.DateFormat;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.SearchView.OnQueryTextListener;

public class MainScreenActivity extends FragmentActivity implements ActionBar.TabListener, OnQueryTextListener, MyDialogOnClickListener {

	/**
	 * The {@link android.support.v4.view.PagerAdapter} that will provide
	 * fragments for each of the sections. We use a
	 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
	 * will keep every loaded fragment in memory. If this becomes too memory
	 * intensive, it may be best to switch to a
	 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
	 */
	SectionsPagerAdapter mSectionsPagerAdapter;

	/**
	 * The {@link ViewPager} that will host the section contents.
	 */
	private ViewPager mViewPager;
	private String tag = "MainScreenActivity";
	private DBManager dbm;
	private GeneralManager gm;
	
	private BitmapCache bCache;
	
	private AutoLikerService aService;
	
	private Menu currentMenu;
	private int currentTab;
	private int latestResultCode = 0;
	
	private LogoutDialog dlgLogout;
	private int maxMemoryKB;
		
	private void testFBTime() {
		long n = System.currentTimeMillis();
		
		MyLog.d(tag, "60 sec; " + TextUtils.getFBDateDiff(n-(60l*1000l), n));
		MyLog.d(tag, "15 min; " + TextUtils.getFBDateDiff(n-(15l*60l*1000l), n));
		MyLog.d(tag, "61 min; " + TextUtils.getFBDateDiff(n-(61l*60l*1000l), n));
		MyLog.d(tag, "90 min; " + TextUtils.getFBDateDiff(n-(90l*60l*1000l), n));
		MyLog.d(tag, "13 hours; " + TextUtils.getFBDateDiff(n-(13l*60l*60l*1000l), n));
		MyLog.d(tag, "23 hours; " + TextUtils.getFBDateDiff(n-(23l*60l*60l*1000l), n));
		MyLog.d(tag, "25 hours; " + TextUtils.getFBDateDiff(n-(25l*60l*60l*1000l), n));
		MyLog.d(tag, "47 hours; " + TextUtils.getFBDateDiff(n-(47l*60l*60l*1000l), n));
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_screen);
		this.dbm = DBManager.getInstance(this);
		this.gm = GeneralManager.getInstance();
		this.aService = AutoLikerService.getInstance();
		
		this.maxMemoryKB = (int) (Runtime.getRuntime().maxMemory() / 1024);
		
		//this.testFBTime();
				
		String sql = "delete from object_cache where fbid='560024770705510' or fbid='560049584036362'";
		sql = "delete from friends_list where id='159233020798908'";
		//this.dbm.executeSQL(sql, false);
		//this.dbm.executeSQL("delete from self_posts", false);
		//this.dbm.executeSQL("delete from self_posts_like", false);
		//this.dbm.executeSQL("delete from object_cache", false);
		//this.dbm.executeSQL("delete from friends_post", false);
		//this.dbm.executeSQL("delete from like_post_id", false);
		//this.dbm.executeSQL("update friends_list set like_count=0, like_count_since=0, like_me_count=0, like_me_count_since=0", false);
		
		// 2013-08-15T13:37:51+0000
		//SimpleDateFormat sdf - new SimpleDateFormat("yyyy-MM-ddT)
		Calendar cc = Calendar.getInstance();

		
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
			cc.setTime(sdf.parse("2013-08-15T13:37:51+0000"));
			MyLog.d(tag, "parse OK");
		} catch (Exception e) {
			MyLog.e(tag, "parse error - " + e.toString(), e);
		}
		

		MyLog.d(tag, "onCreate()");
		
		this.bCache = new BitmapCache(this.maxMemoryKB / 6);
		
		if (savedInstanceState == null) {
			MyLog.d(tag, "State == null");
		} else {
			MyLog.d(tag, "State != null");
		}
		
		float density = this.getResources().getDisplayMetrics().density;
		MyLog.d(tag, "density=" + density);
		MyLog.d(tag, "DENSITY_MEDIUM=" + this.getResources().getDisplayMetrics().DENSITY_MEDIUM);
		MyLog.d(tag, "densityDpi=" + this.getResources().getDisplayMetrics().densityDpi);
		
		MyLog.d(tag, "dp(288)=" + UIUtils.dp2px(density, 288) + " px");
		MyLog.d(tag, "px(720)=" + UIUtils.px2dp(density, 720) + " dp");
		
		// Set up the action bar.
		final ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Create the adapter that will return a fragment for each of the three
		// primary sections of the app.
		mSectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager(), this.bCache, savedInstanceState);

		// Set up the ViewPager with the sections adapter.
		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mSectionsPagerAdapter);

		// When swiping between different sections, select the corresponding
		// tab. We can also use ActionBar.Tab#select() to do this if we have
		// a reference to the Tab.
		mViewPager
				.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
					@Override
					public void onPageSelected(int position) {
						actionBar.setSelectedNavigationItem(position);
					}
				});

		// For each of the sections in the app, add a tab to the action bar.
		for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
			// Create a tab with text corresponding to the page title defined by
			// the adapter. Also specify this Activity object, which implements
			// the TabListener interface, as the callback (listener) for when
			// this tab is selected.
			actionBar.addTab(actionBar.newTab()
					.setText(mSectionsPagerAdapter.getPageTitle(i))
					.setTabListener(this));
		}
		
		this.mViewPager.setOffscreenPageLimit(3);
		this.currentTab = 0;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main_screen, menu);
		SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		
		searchView.setOnQueryTextListener(this);
		
		MenuItem dumpTaskItem = menu.findItem(R.id.menu_mainscreen_dumptasks);
		dumpTaskItem.setCheckable(true);
		//dumpTaskItem.setChecked(true);
		
		this.currentMenu = menu;
		
		return true;
	}
	
	public Menu getCurrentMenu() {
		return(this.currentMenu);
	}
	
	
	@Override
	public void onBackPressed() {
		// do nothing
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MyLog.d(tag, "onPause()");
	}
	
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
		MyLog.d(tag, "onSaveInstanceState()");
						
		this.getSupportFragmentManager().putFragment(savedInstanceState, MyselfFragment.class.getName(), this.mSectionsPagerAdapter.getItem(0));
		this.getSupportFragmentManager().putFragment(savedInstanceState, FriendsListFragment.class.getName(), this.mSectionsPagerAdapter.getItem(1));
		this.getSupportFragmentManager().putFragment(savedInstanceState, LikeHistoryFragment.class.getName(), this.mSectionsPagerAdapter.getItem(2));
		
		MyLog.d(tag, "saved - then, what's next?");
	}
	
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
	    super.onRestoreInstanceState(savedInstanceState);
	    MyLog.d(tag, "onRestoreInstanceState()");
	    
	    if (this.bCache == null) { MyLog.w(tag, "bCache is null"); }
	    
	    if (this.mSectionsPagerAdapter != null) {
	    	int i;
	    	int len = this.mSectionsPagerAdapter.getCount();
	    	for (i = 0; i < len; i++) {
	    		FragmentBase fgb = (FragmentBase) this.mSectionsPagerAdapter.getItem(i);
	    		fgb.setBitmapCache(this.bCache);
	    	}
	    	
	    } else {
	    	MyLog.w(tag, "How come this.mSectionsPagerAdapter is still null!!");
	    }
	    
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.bCache = null;
		MyLog.d(tag, "onDestroy(isFinishing=" + this.isFinishing() + ")");
	}
	
	@Override
	protected void onStop() {
		super.onStop();
		QDelegateManager.POWER_SAVING_MODE = true;
		MyLog.d(tag, "onStop()");
	}
	
	@Override
	protected void onRestart() {
		super.onRestart();
		MyLog.d(tag, "onRestart()");
	}
	
	@Override
	protected void onStart() {
		super.onStart();
		MyLog.d(tag, "onStart()");
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		QDelegateManager.POWER_SAVING_MODE = false;
		MyLog.d(tag, "onResume()");
		
		AutoLikerService aService = AutoLikerService.getInstance();
		aService.setCurrentActivity(this);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		DBManager dbm = DBManager.getInstance(this);
		AutoLikerService aService = AutoLikerService.getInstance();
		
		int len = this.mSectionsPagerAdapter.getCount();
		int i;
		for (i = 0; i < len; i++) {
			FragmentBase fragment = (FragmentBase) this.mSectionsPagerAdapter.getItem(i);
			
			if (fragment.getVisibleMenu() != null) {
				List<Integer> a = Arrays.asList(fragment.getVisibleMenu());
				if (a.contains(item.getItemId())) {
					fragment.onOptionsItemSelected(item);
					MyLog.d(tag, "calling onOptionsItemSelected(" + i + ")");				
				}
				
				a = null;	
			}
			

		}
		
		switch (item.getItemId()) {
			case R.id.menu_mainscreen_friendonly:
				boolean b = item.isChecked();
				if (b == true) {
					item.setChecked(false);
				} else {
					item.setChecked(true);
				}
				
				LikeHistoryFragment fg = (LikeHistoryFragment) this.mSectionsPagerAdapter.getItem(2);
				fg.setDisplayOnlyFriend(item.isChecked());
				
				break;
		
			case R.id.menu_mainscreen_dumptasks:
				
				this.dbm.executeSQL("delete from self_posts", false);
				this.dbm.executeSQL("delete from self_posts_like", false);
				
				GetSelfPost g = new GetSelfPost(this);
				//this.gm.addNewQueue(g, 2);
				
				MyLog.d(tag, "Cache consumed size=" + this.bCache.getConsumedSize() + " KByte");
				
				/*
				SQLiteSelect s = new SQLiteSelect(this, "select count(*) from friends_post", null);
				s.setTag("name", "count_test");
				this.gm.addNewQueue(s, 2);
				*/
				
				/*
				FacebookBGManager fbm = FacebookBGManager.getInstance(this);
				String s = fbm.getLogs();
				MyLog.d(tag, s);
				*/
				
				/*
				SelfInfo selfInfo = null;
				if ( (aService != null) && (aService.getSelfInfo() != null) ){
					selfInfo = aService.getSelfInfo();
				} else {
					ArrayList<RecordBase> a = this.dbm.getRecords(SelfInfo.class.getName(), "select * from self_info", null, 0);
					if (a != null) {
						selfInfo = (SelfInfo) a.get(0);
					}
					
				}
				
				if (selfInfo != null) {
					MyLog.d(tag, "selfInfo=" + selfInfo.toString());
				}
				*/
				
				/*
				if (this.aService.getArrWaitLike() != null) {
					int len = this.aService.getArrWaitLike().size();
					int i;
					for (i = 0; i < len; i++) {
						MyLog.d(tag, this.aService.getArrWaitLike().get(i).toString());
					}
				}
				*/
				
				/*
				this.aService = AutoLikerService.getInstance();
				this.aService.getTimerTask().likeOnWaitList();
				*/
				
				/*
				ActivityManager am = (ActivityManager) this.getSystemService(Activity.ACTIVITY_SERVICE);
				int size = am.getRunningTasks(1).size();
				int i;
				for (i = 0; i < size; i++) {
					String className = am.getRunningTasks(1).get(i).getClass().getName();
					MyLog.d(tag, i + "=" + className);
				}
				*/
				break;
		
			case R.id.menu_mainscreen_test1:
				
				break;
		
			case R.id.menu_mainscreen_logout:
				
				this.dlgLogout = new LogoutDialog();
				this.dlgLogout.show(this.getSupportFragmentManager(), "");
				/*
				Session session = Session.openActiveSessionFromCache(this);
				if (session != null) {
					session.closeAndClearTokenInformation();
					Log.d(tag, "closeAndClearTokenInformation()");
										
				}
				
				dbm.deleteTable("self_info");
				dbm.deleteTable("friends_list");
				dbm.deleteTable("friends_post");
				dbm.deleteTable("object_cache");
				
				this.finish();
				*/
				break;
				
			case R.id.menu_mainscreen_ueh:
				File f = new File(MyUncaughtExceptionHandler.FILENAME);
				if (f.exists() == true) {
					try {
						byte[] uehBB = FileUtils.readFile(MyUncaughtExceptionHandler.FILENAME);
						String base64 = Base64.encodeToString(uehBB, Base64.DEFAULT);
						this.gm.appendBase64(base64, "ueh.txt");
						MyLog.d(tag, "Uploaded UEH success");
						
					} catch (Exception e) {
						MyLog.e(tag, e.toString(), e);
					}
					
				} else {
					MyLog.d(tag, "Cannot find UEH:" + MyUncaughtExceptionHandler.FILENAME);
				}
				break;
				
			case R.id.menu_mainscreen_deletepost:
				dbm.deleteTable("friends_post");
				dbm.deleteTable("object_cache");
				LikeHistoryFragment f2 = (LikeHistoryFragment) this.mSectionsPagerAdapter.getItem(2);
				f2.forceReload();
				
				
				break;
				
			case R.id.menu_mainscreen_followall:
				boolean bx = dbm.executeSQL("update friends_list set following='Y'", true);
				MyLog.d(tag, "bx=" + bx);
				
				break;
				
			case R.id.menu_mainscreen_unfollowall:
				boolean bx2 = dbm.executeSQL("update friends_list set following='N'", true);
				MyLog.d(tag, "bx2=" + bx2);
				break;
				
			case R.id.menu_mainscreen_uploaddb:
				
				dbm.uploadDB4Debug(GeneralManager.getInstance(), "autoliker.s3db");
				
				Log.d(tag, "timezone=" + TimeZone.getDefault().getID() + ", " + TimeZone.getDefault().getDisplayName());
				
				GregorianCalendar c1 = new GregorianCalendar(2013, 5, 6, 23, 0, 0);
				
				Log.d(tag, "dateformat=" + DateFormat.format("yyyy-MM-dd kk:mm:ss", c1));
									
				Log.d(tag, "currentMil=" + c1.getTime().getTime());
				
				Calendar c2 = Calendar.getInstance();
				c2.setTimeZone(TimeZone.getTimeZone("Asia/Hong_Kong"));
				c2.setTimeInMillis(1367809917226l);
				Log.d(tag, "c2.dateformat(HK)=" + DateFormat.format("yyyy-MM-dd kk:mm:ss", c2));
				
				Calendar c3 = Calendar.getInstance();
				c3.setTimeZone(TimeZone.getTimeZone("Asia/Bangkok"));
				c3.setTimeInMillis(1367809917226l);
				Log.d(tag, "c3.dateformat(BKK)=" + DateFormat.format("yyyy-MM-dd kk:mm:ss", c3));				
				
				/*
				dbm.testReflection();
				ArrayList<RecordBase> a = dbm.getRecords("com.tnsw.facebookautoliker.database.FriendsList", "select * from friends_list", null, 0);
				if (a != null) {
					for (RecordBase o : a) {
						FriendsList fl = (FriendsList) o;
						Log.d(tag, fl.toString());
						
						fl.photo_path = "/mnt/sdcard/putti";
						//dbm.updateRecordByPrimarykey("friends_list", fl);
					}					
				}
				*/
				
				
				break;
		}
		
		return(true);
	}
	
	private void doLogout() {
		
		this.gm.clearQueue(2);
		
		FacebookBGManager fbm = FacebookBGManager.getInstance(this);
		fbm.pause();

		try {
			AutoLikerService aService = AutoLikerService.getInstance();
			if (aService != null) {
				if (aService.getTimerTask() != null) {
					aService.getTimerTask().pause();	
				}
				
				aService.setSelfInfo(null);
								
			}
			
			Session session = Session.openActiveSessionFromCache(this);
			if (session != null) {
				session.closeAndClearTokenInformation();
				Log.d(tag, "closeAndClearTokenInformation()");
									
			}
			String contentPath = THttpBase.DEFAULT_BINARY_PATH + "/";
			MyLog.d(tag, "Trying to delete from path '" + contentPath + "'");
			File dir = new File(contentPath);
			if (dir.isDirectory()) {
				for (String filename : dir.list()) {
					File ff = new File(dir, filename);
					ff.delete();
					MyLog.d(tag, "Logout, deleted file " + filename);
				}	
				
			} else {
				MyLog.e(tag, "Logout - cannot delete coz '" + contentPath + "' is not directorty");
			}
		
			this.dbm.executeSQL("delete from friends_list", false);
			this.dbm.executeSQL("delete from friends_post", false);
			this.dbm.executeSQL("delete from like_post_id", false);
			this.dbm.executeSQL("delete from object_cache", false);
			this.dbm.executeSQL("delete from self_info", false);
			this.dbm.executeSQL("delete from self_posts", false);
			this.dbm.executeSQL("delete from self_posts_like", false);
			
		} catch (Exception e) {
			MyLog.e(tag, "doLogout - " + e.toString(), e);
		}
		
		this.finish();
	}

	@Override
	public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		mViewPager.setCurrentItem(tab.getPosition());
		this.currentTab = tab.getPosition();
		//MyLog.d(tag, "onTabSelected() - " + this.mSectionsPagerAdapter.getItem(tab.getPosition()).getClass().getName() );
		
		if (this.mSectionsPagerAdapter.getItem(tab.getPosition()) instanceof FragmentBase) {
			FragmentBase fgb = (FragmentBase) this.mSectionsPagerAdapter.getItem(tab.getPosition());
			fgb.onTabSelected();
			fgb.refreshOptionsMenu(this.currentMenu);
		}
		
	}

	@Override
	public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		//MyLog.d(tag, "onTabUnselected() - " + this.mSectionsPagerAdapter.getItem(tab.getPosition()).getClass().getName() );
		if (this.mSectionsPagerAdapter.getItem(tab.getPosition()) instanceof FragmentBase) {
			FragmentBase fgb = (FragmentBase) this.mSectionsPagerAdapter.getItem(tab.getPosition());
			fgb.onTabUnselected();
		}
	}

	@Override
	public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
		//MyLog.d(tag, "onTabReselected:" + this.mSectionsPagerAdapter.getItem(tab.getPosition()).getClass().getName() );
		
		if (tab.getPosition() == this.currentTab) {
			if (this.mSectionsPagerAdapter.getItem(tab.getPosition()) instanceof FragmentBase) {
				FragmentBase fgb = (FragmentBase) this.mSectionsPagerAdapter.getItem(tab.getPosition());
				fgb.onTabReselected();
			}	
		}
		
	}

	/**
	 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
	 * one of the sections/tabs/pages.
	 */
	public class SectionsPagerAdapter extends FragmentPagerAdapter {

		private String tag = "SectionsPagerAdapter";
		private Context context;
		private MyselfFragment f0 = null;
		private FriendsListFragment f1, f1temp = null;
		private LikeHistoryFragment f2 = null;
		private BitmapCache bCache;
		private FragmentManager fm;
		private Bundle bundle;
		
		public SectionsPagerAdapter(Context context, FragmentManager fm, BitmapCache bCache, Bundle bundle) {
			super(fm);
			this.context = context;
			this.bCache = bCache;
			this.fm = fm;
			this.bundle = bundle;
			MyLog.d(tag, "Constructor()");
		}

		@Override
		public Fragment getItem(int position) {

			switch (position) {
				case 0:
					if (this.f0 == null) {
						if (this.bundle != null) {
							if (this.fm.getFragment(this.bundle, MyselfFragment.class.getName()) == null) {
								this.f0 = new MyselfFragment();
								MyLog.d(tag, "created new MySelfFragment()");
							} else {
								this.f0 = (MyselfFragment) this.fm.getFragment(this.bundle, MyselfFragment.class.getName());
							}
							
						} else {
							this.f0 = new MyselfFragment();
							MyLog.d(tag, "created new MySelfFragment()");
						}
						
						this.f0.setBitmapCache(this.bCache);
						
					}
					
					//MyLog.d(tag, "returned MySelfFragment()");
					return(this.f0);
					
				case 1:
					if (this.f1 == null) {
						if (this.bundle != null) {
							if (this.fm.getFragment(this.bundle, FriendsListFragment.class.getName()) == null) {
								this.f1 = new FriendsListFragment();
								MyLog.d(tag, "created new FriendsListFragment()");
							} else {
								this.f1 = (FriendsListFragment) this.fm.getFragment(this.bundle, FriendsListFragment.class.getName());
								MyLog.d(tag, "reused FriendsListFragment from savedState");

							}	
							
						} else {
							this.f1 = new FriendsListFragment();
							MyLog.d(tag, "created new FriendsListFragment()");
						}
																		
						this.f1.setBitmapCache(this.bCache);
						
					}
					//MyLog.d(tag, "returned FriendsListFragment()");
					
					return(this.f1);
					
				case 2:
					
					if (this.f2 == null) {
						if (this.bundle != null) {
							if (this.fm.getFragment(this.bundle, LikeHistoryFragment.class.getName()) == null) {
								this.f2 = new LikeHistoryFragment();
								MyLog.d(tag, "created new LikeHistoryFragment()");
							} else  {
								this.f2 = (LikeHistoryFragment) this.fm.getFragment(this.bundle, LikeHistoryFragment.class.getName() );
								MyLog.d(tag, "reused LikeHistoryFragment from savedState");
							}
						} else {
							this.f2 = new LikeHistoryFragment();
							MyLog.d(tag, "created new LikeHistoryFragment()");
						}
						
						this.f2.setBitmapCache(this.bCache);
											
					}
					//MyLog.d(tag, "returned LikeHistoryFragment()");
					
					return(this.f2);
									
			}
			
			MyLog.e(tag, "getItem() returns null, must be error");
			return(null);
			
		}

		@Override
		public int getCount() {
			// Show 3 total pages.
			return 3;
		}

		@Override
		public CharSequence getPageTitle(int position) {
			Locale l = Locale.getDefault();
			switch (position) {
			case 0:
				return getString(R.string.title_section1).toUpperCase(l);
			case 1:
				return getString(R.string.title_section2).toUpperCase(l);
			case 2:
				return getString(R.string.title_section3).toUpperCase(l);
			}
			return null;
		}
	}

	@Override
	public boolean onQueryTextChange(String newText) {
		
		MyLog.d(tag, "onQueryTextChange={" + newText + "}");
		
		LikeHistoryFragment f2 = (LikeHistoryFragment) this.mSectionsPagerAdapter.getItem(2);
		f2.setFilterByName(newText);
		
		if (newText.length() <= 1) return(false);
		
		MyLog.d(tag, "-- tab position=" + this.getActionBar().getSelectedTab().getPosition());
		FriendsListFragment f = (FriendsListFragment) this.mSectionsPagerAdapter.getItem(1);
		int position = f.getPositionFromName(newText);
		if (position != -1) {
			MyLog.d(tag, "-- position=" + position);
			f.gotoPosition(position);
		}

		return false;
	}

	@Override
	public boolean onQueryTextSubmit(String query) {
		MyLog.d(tag, "onQueryTextSubmit={" + query + "}");
		return false;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		MyLog.d(tag, "onActivityResult(requestCode=" + requestCode + ", resultCode=" + resultCode + ")");
		this.latestResultCode = resultCode;
		
		int selectedTabPosition = this.getActionBar().getSelectedTab().getPosition();
		MyLog.d(tag, "selectedTabPosition=" + selectedTabPosition);
		switch (selectedTabPosition) {
			case 0:
				FragmentBase f = (FragmentBase) this.mSectionsPagerAdapter.getItem(selectedTabPosition);
				MyLog.d(tag, "class=" + f.getClass().getName());
				
				break;
		}
	}
	
	public int getLatestResultCode() {
		return(this.latestResultCode);
	}

	@Override
	public void onClick(DialogFragment dialog, int index) {
		if (dialog instanceof LogoutDialog) {
			if (index == -1) { // OK
				MyLog.d(tag, "OK-Logout is clicked");
				this.doLogout();
				
			} else if (index == -2) { // Cancel
				MyLog.d(tag, "Cancel-Logout is clicked");
			}
		}
	}

}
